use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Game {
    level: u32,
    score: u32,
    is_paused: bool,
    grass_positions: Vec<(f64, f64)>,
    player_x: f64,
    player_y: f64,
}

#[wasm_bindgen]
impl Game {
    pub fn new() -> Game {
        Game {
            level: 1,
            score: 0,
            is_paused: false,
            grass_positions: vec![],
            player_x: 0.0,
            player_y: 0.0,
        }
    }

    pub fn init_level(&mut self, level: u32) {
        self.level = level;
        self.grass_positions.clear();
        
        // 根据关卡生成不同数量的草
        let grass_count = match level {
            1 => 10,
            2 => 15,
            3 => 20,
            _ => 25,
        };

        // 随机生成草的位置
        for _ in 0..grass_count {
            let x = js_sys::Math::random() * 800.0;
            let y = js_sys::Math::random() * 600.0;
            self.grass_positions.push((x, y));
        }
    }

    pub fn move_player(&mut self, x: f64, y: f64) {
        if !self.is_paused {
            self.player_x = x;
            self.player_y = y;
            self.check_collision();
        }
    }

    pub fn toggle_pause(&mut self) {
        self.is_paused = !self.is_paused;
    }

    pub fn is_level_complete(&self) -> bool {
        self.grass_positions.is_empty()
    }

    fn check_collision(&mut self) {
        self.grass_positions.retain(|(grass_x, grass_y)| {
            let distance = ((self.player_x - grass_x).powi(2) + 
                          (self.player_y - grass_y).powi(2)).sqrt();
            if distance < 30.0 {
                self.score += 10;
                false
            } else {
                true
            }
        });
    }

    pub fn get_grass_positions(&self) -> Vec<f64> {
        self.grass_positions.iter()
            .flat_map(|(x, y)| vec![*x, *y])
            .collect()
    }

    pub fn get_score(&self) -> u32 {
        self.score
    }

    pub fn get_level(&self) -> u32 {
        self.level
    }
} 